/**
 * 支持错误重试的Promise封装
 * @param {Function} executor - 返回Promise的函数
 * @param {Object} options - 配置项
 * @param {number} options.retries - 最大重试次数（默认3次）
 * @param {number} options.delay - 重试间隔毫秒数（默认1000ms）
 * @param {Function} [options.onRetry] - 每次重试前的回调
 */

function retryablePromise(
  executor,
  { retries = 3, delay = 1000, onRetry = null } = {}
) {
  return new Promise((resolve, reject) => {
    const attempt = (remainingAttempts) => {
      executor()
        .then(resolve)
        .catch((error) => {
          console.log("remainingAttempts: ", remainingAttempts);
          if (remainingAttempts > 0) {
            if (onRetry) onRetry(error, retries - remainingAttempts + 1);
            setTimeout(() => attempt(remainingAttempts - 1), delay);
          } else {
            reject(error);
          }
        });
    };
    attempt(retries);
  });
}

const promise = () =>
  new Promise((resolve, reject) => {
    console.log("2222222222222222222");
    setTimeout(() => reject("111111111111111111111"), 2 * 1000);
  });

retryablePromise(promise, {
  retries: 4,
  delay: 2000,
  onRetry: (error, count) => {
    console.log("error,count: ", error, count);
  },
})
  .then(console.log)
  .catch(console.log);
